package com.lagou.niancheng.lagou.service.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * com.lagou.niancheng.lagou.service.common.ExtRequestAop
 *
 * @author 大犬
 * @date 2020/7/1
 */
public class ExtRequestAop implements BeanPostProcessor {

    private String extPackage;

    public ExtRequestAop(String extPackage) {
        this.extPackage = extPackage;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Package aPackage = bean.getClass().getPackage();
        if (aPackage == null) {
            return bean;
        }
        if (aPackage.getName().startsWith(extPackage)) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(bean.getClass());
            enhancer.setCallback(new RequestProxy());
            return enhancer.create();
        }
        return bean;
    }
    public static class RequestProxy implements MethodInterceptor {

        @Override
        public Object intercept(Object o, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
            Object result = methodProxy.invoke(o, params);
            if (result instanceof Result) {
                Result methodResult = (Result) result;
                if (methodResult.isSuccess()) {
                    return methodResult;
                } else {
                    throw new LagouException(CommonErrorCode.REMOTE_REQUEST_ERROR, methodResult.getErrorMsg());
                }
            }

            return result;
        }
    }

}

